package data.join.com.carapi;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.WebSocket;
import com.koushikdutta.async.http.server.AsyncHttpServer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import data.join.com.R;
import data.join.com.carrecord.MainActivity;
import data.join.com.utils.MyLog;
import data.join.com.utils.QuickShPref;

import static data.join.com.carapi.API.CollisionSensitivityLow;

/**
 * Created by Administrator on 2017/9/29.
 */

public class ApiPref {
    public static final String TAG = ApiPref.class.getSimpleName();

    public final static String ACTION_CAR_WAKEUP = "com.car.syswakeup";

    public static final String ACTION_REVERSE_GEAR_UI_STATUS = "com.car.dvr.reverse.gear.popup";
    public static final String IN_REVERSE_GEAR = "is.reverse.gear";

    private API mApi;

    private static ApiPref mApiPref;

    private Context mContext;

    CountDownLatch countDownLatch;
    String takeVideoPath;

    Handler mHandler = new Handler();

    private ApiPref(Context context){
        mApi = new API(context);
        mContext = context;
        mContext.registerReceiver(broadcastReceiver,new IntentFilter(CarIntents.ACTION_CAMERA_SNAPSHOT_CALLBACK));
        mContext.registerReceiver(backDriverReceiver,new IntentFilter(ACTION_REVERSE_GEAR_UI_STATUS));
    }

    public static ApiPref getInstance(Context context){
        if(mApiPref == null){
            mApiPref = new ApiPref(context);
        }
        return mApiPref;
    }

    public void initConfig(){

        mApi.setAutoSleepTime(0);

        mApi.setWakeupLockWhiteList(null);
        mApi.setProperty("persist.sys.app.keepalive",mContext.getPackageName());
        mApi.setProperty("sys.rtc.packages",mContext.getPackageName());
        mApi.setProperty("ro.tts.statusmore",mContext.getString(R.string.voice_app_name));

        mApi.disableForwarding();
        mApi.enableForwarding("basket.wangjile.cn");

        initDeviceConfig();
    }

    public void startUpdate(String path){
        mApi.installApk(path,mContext.getPackageName(), MainActivity.class.getName());
    }

    public synchronized String takeVideo(int cameraId,int startTime,int endTime){

        wakeUpRecord();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        takeVideoPath = null;

        countDownLatch = new CountDownLatch(1);

        mApi.takeVideo(cameraId,startTime,endTime,false,false);

        try {
            if(countDownLatch.getCount() >= 1) {
                countDownLatch.await(60, TimeUnit.SECONDS);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        countDownLatch = null;

        return takeVideoPath;
    }

    String takePhotoJson;
    CountDownLatch photoLatch;
    public synchronized PhotoResult takePhoto(){
        PhotoResult photoResult = null;

        takePhotoJson = null;

        photoLatch = new CountDownLatch(1);

        mApi.takePicture(0, new API.TakeCallback() {
            @Override
            public void onTakeProgress(int progressPrecentage) {

            }

            @Override
            public void onTakeResult(String jsonString) {
                takePhotoJson = jsonString;

                photoLatch.countDown();
            }
        });

        try {
            if(photoLatch.getCount() >= 1) {
                photoLatch.await(20, TimeUnit.SECONDS);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        MyLog.D(TAG,"takePhotoJson ="+takePhotoJson);
        try {
            photoResult = new Gson().fromJson(takePhotoJson, PhotoResult.class);
        }catch (Exception e){
            e.printStackTrace();
        }

        return photoResult;
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int ret = intent.getIntExtra("ret", -1);
            String error = intent.getStringExtra("error");
            String path = intent.getStringExtra("path");

            MyLog.D(TAG, "ret = " + ret + " error = " + (error != null ? error : "")
                    + " path = " + (path != null ? path : ""));

            takeVideoPath = path;
            if(countDownLatch != null)
                countDownLatch.countDown();
        }
    };

    private void wakeUpRecord(){
        Intent intent = new Intent(ACTION_CAR_WAKEUP);
        intent.putExtra("reason", "recordvideo");
        mContext.sendBroadcast(intent);

    }

    private BroadcastReceiver backDriverReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean ret = intent.getBooleanExtra(IN_REVERSE_GEAR,false);

            ApiMessage message = new ApiMessage(IN_REVERSE_GEAR,ret+"");
            WebSocketServer.getInstance().sendMassage(message);

            MyLog.D(TAG,"backDriverReceiver is.reverse.gear="+ret);
        }
    };

    public static final String GSENSOR_ENABLE = "gsensor_enable";
    public static final String KEY_FRONT_CAMERA = "front_quality";

    private void initDeviceConfig(){

        boolean setApiComplete = QuickShPref.getInstance().getBoolean(QuickShPref.InitDevConfig);

        if(setApiComplete)
            return;

        String url = "ws://" + "127.0.0.1" + ":" + 8081;

        AsyncHttpClient.getDefaultInstance().websocket(url,null,new AsyncHttpClient.WebSocketConnectCallback() {
            @Override
            public void onCompleted(Exception ex, final WebSocket webSocket) {

                Log.d(TAG,"websocket onCompleted webSocket==null is " + (webSocket==null));

                if(webSocket == null){
                    return;
                }

                if (ex != null) {
                    ex.printStackTrace();
                    return;
                }

                setQuality(webSocket);

                //disableWakeUp(webSocket);

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        webSocket.close();
                        mApi.restartDVR(0);
                        QuickShPref.getInstance().putValueObject(QuickShPref.InitDevConfig,true);
                    }
                },1000);
            }
        });

    }

    private void setQuality(WebSocket webSocket){
        try {
            JSONObject jso = new JSONObject();

            jso.put("f", "set");

            JSONObject item = new JSONObject();
            item.put(KEY_FRONT_CAMERA, "normal");
            jso.put("dvr", item);

            webSocket.send(jso.toString());

            MyLog.D(TAG,"setQuality normal complete");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void disableWakeUp(WebSocket webSocket){
        try {
            JSONObject jso = new JSONObject();
            jso.put("f", "set");
            JSONObject item = new JSONObject();
            item.put(GSENSOR_ENABLE, 0);
            jso.put("generic", item);

            webSocket.send(jso.toString());

            MyLog.D(TAG,"disableSuspendCollision complete");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

